import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';

@Injectable()
export class AuthService implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly jwtService: JwtService,
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const request: Request = context.switchToHttp().getRequest();

    const requireLogin = this.reflector.getAllAndOverride<boolean>(
      'require-login',
      [context.getHandler(), context.getClass()],
    );

    if (!requireLogin) {
      return true; // 不需要登录，直接放行
    }

    const authorization = request.headers.authorization;

    if (!authorization) {
      throw new UnauthorizedException('用户未登录');
    }
    const secret = 'hh2837183';
    try {
      const token = authorization.split(' ')[1];
      const user = this.jwtService.verify(token, { secret });
      request['user'] = user; // 将用户信息存入 request

      return true; // 鉴权通过
    } catch (error) {
      throw new UnauthorizedException('token 失效，请重新登录');
    }
  }
}
